﻿#region File and License Information
/*
<File>
	<License>
		Copyright © 2009 - 2017, Daniel Vaughan. All rights reserved.
		This file is part of Calcium (http://calciumsdk.net), 
		which is released under the MIT License.
		See file /Documentation/License.txt for details.
	</License>
	<CreationDate>$CreationDate$</CreationDate>
</File>
*/
#endregion

using System.Threading.Tasks;

namespace Outcoder.Concurrency
{
	/* TODO: DV comment. */
	public static class TaskUtility
	{
		public static Task FromResult(this Task task)
		{
			return CreateTaskWithResult();
		}

		public static Task CreateTaskWithResult()
		{
#if !SILVERLIGHT
			return Task.FromResult(0);
#else
			var taskSource = new TaskCompletionSource<int>();
			taskSource.SetResult(0);
			return taskSource.Task;
#endif
		}

		public static async Task Yield(uint depth)
		{
			if (depth == 0)
			{
				return;
			}

			for (int i = 0; i < depth; i++)
			{
				await Task.Yield();
				await Yield(depth - 1);
			}
		}

#if __IOS__ || __ANDROID__

		public static Task<T> FromException<T>(System.Exception exception)
		{
			var source = new TaskCompletionSource<T>();
			source.SetException(exception);
			return source.Task;
		}

		public static Task FromException(System.Exception exception)
		{
			var source = new TaskCompletionSource<object>();
			source.SetException(exception);
			return source.Task;
		}
#endif

	}
}
